from machine import I2C

"""
DS1307 RTC Driver

DS1307实时时钟驱动模块。
提供时间读取和设置功能。

特性：
- 支持24小时制
- 支持年月日时分秒的读写
- 自动处理BCD编码转换
"""

class DS1307:
    def __init__(self, i2c):
        self.i2c = i2c
        self.addr = 0x68
        
    def _bcd2dec(self, bcd):
        return (((bcd & 0xf0) >> 4) * 10 + (bcd & 0x0f))
    
    def _dec2bcd(self, dec):
        tens, units = divmod(dec, 10)
        return (tens << 4) + units
        
    def datetime(self):
        data = self.i2c.readfrom_mem(self.addr, 0, 7)
        ss = self._bcd2dec(data[0] & 0x7F)
        mm = self._bcd2dec(data[1])
        if data[2] & 0x40:
            hh = self._bcd2dec(data[2] & 0x1F)
            if data[2] & 0x20:
                hh += 12
        else:
            hh = self._bcd2dec(data[2] & 0x3F)
        wday = self._bcd2dec(data[3])
        DD = self._bcd2dec(data[4])
        MM = self._bcd2dec(data[5])
        YY = self._bcd2dec(data[6])
        return (YY, MM, DD, wday, hh, mm, ss)
    
    def set_datetime(self, year, month, day, weekday, hour, minute, second):
        data = bytearray(7)
        data[0] = self._dec2bcd(second)
        data[1] = self._dec2bcd(minute)
        data[2] = self._dec2bcd(hour)
        data[3] = self._dec2bcd(weekday)
        data[4] = self._dec2bcd(day)
        data[5] = self._dec2bcd(month)
        data[6] = self._dec2bcd(year)
        self.i2c.writeto_mem(self.addr, 0, data)